package com.my.study.utils;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;

import java.util.concurrent.TimeUnit;

@Slf4j
public class RedissonLockUtil {

    private static Redisson redisson = SpringBeanUtil.getBean(Redisson.class);

    public static String deduceStock(String lockKey, long time, BusinessService businessService) {
        RLock redissonLock = redisson.getLock(lockKey);
        String result;
        try {
            /*
             *  boolean isGetLock = redissonLock.tryLock(50, 20, TimeUnit.SECONDS);
             *  (1) T1尝试加锁成功, 返回true, 锁在20s后自动过期; (没有watch dog)
             *  (2) T2尝试加锁失败, 在50s后停止重试, 返回false;
             *  ======================================================
             *  (1) T1加锁成功后直接返回, 20s后锁自动过期; (没有watch dog)
             *  (2) T2加锁失败后会不停的去重试;
             *
             */
            // 获取锁
            redissonLock.lock(time, TimeUnit.SECONDS);
            log.info("------ 执行业务自定义逻辑逻辑 ----start------");
            result = businessService.executor();
        } finally {
            redissonLock.unlock();
        }
        return result;
    }

    @FunctionalInterface
    public interface BusinessService {
        String executor();
    }
}
